<?php
declare(strict_types=1);

namespace Modules\Web\Service;

use HiCommon\Repository\CouponGrantDetailRepository;
use HiCommon\Repository\CouponsRepository;
use HiCommon\Repository\UsersRepository;
use HiCommon\Repository\OrderRepairstoreRepository;
use HiCommon\Repository\OrderCheckpointRepository;


class CouponService extends BaseService
{

/**
	 * 	商户APP扫码用户提供的二维码获得参数 ， 并携带参数请求优惠券、用户信息
	 *	hinq 2019 10 24 
	 *	$ticket_num string   领取优惠券时生成的唯一优惠券券号
	 *  扫码只能使用洗车券（pid为1）
	 **/
	public function coupon_detail( string $ticket_num = null ){

		try {
			if( empty( $ticket_num ) ){
				return ['state'=> 1,'msg'=>'参数错误','data'=>[],'error'=>''];
			}
			$arr_where = ['ticket_num'=>$ticket_num ];
			$arr_option['field'] = ['id','user_id','coupon_id','ticket_num','over_at','status'];
			$arr_option['with'] = ['getUserInfo','getCouponInfo'];
			$arr_list = CouponGrantDetailRepository::get_one_where( (array)$arr_where , (array) $arr_option );

            if( empty( $arr_list->first() ) ){
			    return hello_error('参数错误');
            }
            $arr_list = $arr_list->toArray();

//			//优惠券的过期时间  <   当前时间
//			if( $arr_list['over_at'] < time() ){
//				return ['state'=> 1,'msg'=>'该优惠券已过期，不可使用','data'=>[],'error'=>''];
//			}
//            if( $arr_list['status'] == 2 ){
//                return ['state'=> 1,'msg'=>'该优惠券已使用，不可使用','data'=>[],'error'=>''];
//            }
//            if( $arr_list['status'] == 3 ){
//                return ['state'=> 1,'msg'=>'该优惠券已过期，不可使用','data'=>[],'error'=>''];
//            }

            return hello_success('ok',$arr_list);
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}



	/**
	 *	使用扫码扫出来的优惠券
	 *	hinq 2019 10 24
	 *
	 ***/
	public function coupon_use( string $ticket_num = null ){
		try {

			if( empty( $ticket_num ) ){
				return ['state'=>1 ,'msg'=>'参数错误','data'=>[],'error'=>''];
			}
			//获取当前优惠券的信息
            $where['ticket_num'] = $ticket_num;
			$arr_info = CouponGrantDetailRepository::get_one_where( (array) $where );

			if( empty( $arr_info->first() ) ){
			    return hello_error('参数错误');
            }
            $arr_info = $arr_info ->toArray();

            if( $arr_info['pid'] != 1 ){
                return hello_error('优惠券类型错误');
            }

			if( $arr_info['status'] != 1 ){
                if( $arr_info['status'] == 2 && !empty( $arr_info['repairstore_id'] ) ){
                    return hello_error('优惠券已使用，请勿重复使用');
                }elseif( $arr_info['status'] == 3 ){
                    return hello_error('优惠券已过期，不可使用');
                }else{
                    return hello_error('优惠券已使用或已过期，不可使用');
                }
            }
            // 有效期 <  当前时间
			if( $arr_info['over_at'] < time() ){
			    return hello_error('该优惠券已过期，不可使用');
//				return ['state'=>1 ,'msg'=>'该优惠券已过期，不可使用','data'=>[],'error'=>''];
			}
			//更新优惠券的状态信息
			$repairstore_id = get_web_shop_id();   //当前商户的商户id
			$data['id'] = $arr_info['id'];
			$data['repairstore_id'] = $repairstore_id;
			$data['status'] = 2;   //  1：未使用  2： 已使用  3：已过期
			$data['use_msg'] = '商户app扫码使用优惠券';
			$data['use_type'] = 1;   // 1： 扫码使用  2：后台搜索券号使用  3:订单使用
			$res = CouponGrantDetailRepository::edit_one( (array) $data );
			$result = hi_check_res($res,'edit_one');
	        if ($result['state'] != 0) {
	            return ['state'=> 1,'msg'=>'使用失败','data'=>[],'error'=>''];
	        }
	        return hello_success('ok');
//	        return ['state'=> 0,'msg'=>'ok','data'=>[],'error'=>''];
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}




	/**
	 *	商户获取已在该商户商用的优惠券列表
	 *	hinq 2019 10 24
	 *	只获取已经使用的优惠券
	 **/
	public function use_coupon_list( array $arr_search = [] ){

		try {
            $repairstore_id = get_web_shop_id();   //当前商户的商户id
			$arr_option['where'] = [ 'repairstore_id'=> $repairstore_id ,'status' => 2 ];
			$arr_option['with'] = ['getUserInfo','getCouponInfo'];
			$arr_option['field'] = ['id','user_id','coupon_id','ticket_num','status','updated_at','pid','over_at','created_at'];
			$arr_list = CouponGrantDetailRepository::get_list( (array) $arr_search , (array) $arr_option )->toArray();

			$data = $arr_list['data'];
			$pids = [1=>'洗车券',2=>'满减券',3=>'折扣券'];
			$temp = [];
			foreach ( $data as $key => &$value) {
				if( $value['pid'] == 1 ){
                    $temp[$key]['pid_msg'] = $pids[$value['pid']];
				}else if( $value['pid'] == 2 ){
                    $temp[$key]['pid_msg'] = '满'.floatval($value['get_coupon_info']['price_all']).'元减'.floatval( $value['get_coupon_info']['price']).'元';
				}else if( $value['pid'] == 3 ){
                    $temp[$key]['pid_msg'] = '满'.floatval( $value['get_coupon_info']['price_all'] ).'元打'.floatval( $value['get_coupon_info']['discount_num']).'折';
				}
                $temp[$key]['pid_name'] = $pids[$value['pid']];
                $temp[$key]['id'] = $value['id'];
                $temp[$key]['ticket_num'] = $value['ticket_num'];
                $temp[$key]['status'] = $value['status'];
                $temp[$key]['updated_at'] =  $value['updated_at'];
                $temp[$key]['created_at'] = date("Y-m-d", strtotime( $value['created_at'] ) );
                $temp[$key]['over_at'] = date("Y-m-d", $value['over_at'] );
                $temp[$key]['pid'] = $value['pid'];
                $temp[$key]['user']['username'] = $value['get_user_info']['username'];
                $temp[$key]['user']['id'] = $value['get_user_info']['id'];
                $temp[$key]['user']['nickname'] = $value['get_user_info']['nickname'];
                $temp[$key]['user']['head_img'] = $value['get_user_info']['head_img'];
                $temp[$key]['coupon']['id'] = $value['get_coupon_info']['id'];
                $temp[$key]['coupon']['name'] = $value['get_coupon_info']['name'];
                $temp[$key]['coupon']['price'] = $value['get_coupon_info']['price'];
                $temp[$key]['coupon']['discount_num'] = $value['get_coupon_info']['discount_num'];
                $temp[$key]['coupon']['price_all'] = $value['get_coupon_info']['price_all'];
                $temp[$key]['coupon']['ticket_num'] = $value['get_coupon_info']['ticket_num'];
                $temp[$key]['coupon']['content'] = $value['get_coupon_info']['content'];
			}
			$temp = [
				'data' => $temp,
				'page_data'=>[
		            'current_page'=>$arr_list['current_page'],
		            'last_page'=>$arr_list['last_page'],
		            'per_page'=>$arr_list['per_page'],
		            'total'=>$arr_list['total'],
	          	],
			];
			return ['state'=> 0,'msg'=>'ok','data'=>$temp,'error'=>''];	
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}
}
